package com.jiayou.activity

import android.content.res.ColorStateList
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import cn.hutool.http.HttpRequest
import cn.hutool.json.JSONUtil
import com.jiayou.R
import com.jiayou.tool.AndroidTool
import kotlinx.android.synthetic.main.activity_publish_moment.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.*
import kotlin.concurrent.thread

class PublishMomentActivity : AppCompatActivity(), View.OnClickListener {

    private val properties = Properties()
    lateinit var uri: String


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_publish_moment)
        AndroidTool.fullScreen(this)


        properties.load(application.assets.open("im.properties"))
        uri = properties["im.uri"].toString() + ":" + properties["im.port"].toString()

        editText.addTextChangedListener {
            if (it!!.isNotEmpty()) {
                imageView3.isClickable = true
                imageView3.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#33CC33"))
                imageView3.setTextColor(Color.parseColor("#FFFFFF"))
            } else {
                imageView3.isClickable = false
                imageView3.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#F2F2F2"))
                imageView3.setTextColor(Color.parseColor("#969696"))
            }
        }

        back.setOnClickListener(this)
        imageView3.setOnClickListener(this)
    }

    override fun onClick(p0: View) {
        when (p0.id) {
            R.id.back -> {
                finish()
            }
            R.id.imageView3 -> {
                thread {
                    val resoult = JSONUtil.parseObj(
                        HttpRequest.post("http://${uri}/im/moment/addNew")
                            .form(
                                mapOf(
                                    "username" to MainActivity.ID,
                                    "description" to editText.text.toString()
                                )
                            )
                            .header("auth", "73913da7-508b-4646-b8ae-ef6458f41153")
                            .execute()
                            .body()
                    )

                    runBlocking {
                        withContext(Dispatchers.Main) {
                            Toast.makeText(this@PublishMomentActivity, resoult["data"].toString(), Toast.LENGTH_SHORT).show()
                        }
                    }
                    finish()
                }
            }
        }
    }

    override fun onBackPressed() = finish()
}